<template>
  <van-popup v-model:show="state.isShow" class="w-full" style="height: 100%" position="right">
    <div class="page">
      <global-header :title="`${title}：${username} 分数操作`" @back="state.isShow = false" />
      <main class="page-main !overflow-hidden ">
        <van-cell
          title="操作类型"
          :value="form.action == 4 ? '上分' : '下分'"
          is-link
          @click="actionSelect.handleShow()"
        />
        <van-field label="金额" v-model="form.amount" type="digit" input-align="right" />

        <div class="w-[0] absolute left-[-10px]">
          <ActionSelect
            ref="actionSelect"
            v-model:val="form.action"
            title="操作类型"
            :columns="[
              { text: '上分', value: 4 },
              { text: '下分', value: 6 }
            ]"
          />
        </div>
      </main>
      <div class="p-[15px] bg-[#FFFFFF]">
        <div class="flex gap-[10px]">
          <van-button
            @click="confirm"
            class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF] rounded-[5px]"
            :loading="state.updating"
            block
          >
            保存
          </van-button>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
import { debounce } from "lodash-es";
import { reqUpDownPoints } from "@/api/user";
import { toast } from "@/utils/toast";

const props = withDefaults(
  defineProps<{
    username?: string;
    uid?: number;
    type?: "user" | "robot";
  }>(),
  {
    username: "",
    uid: 0,
    type: "user"
  }
);
const emit = defineEmits(["update"]);

const actionSelect = ref();

const title = computed(() => (props.type == "user" ? "用户" : "机器人"));
const state = reactive({
  isShow: false,
  updating: false
});
const form = reactive({
  action: 4,
  amount: 0
});
const closed = () => {
  form.action = 4;
  form.amount = 0;
  state.isShow = false;
};
const open = () => {
  state.isShow = true;
};

const confirm = debounce(
  async () => {
    if (!props.uid) {
      toast.fail("非法操作");
      return false;
    }
    if (!form.action) {
      toast.fail("请选择分数操作");
      return false;
    }
    if (form.amount === 0) {
      toast.fail("操作金额为0");
      return false;
    }
    if (!form.amount) {
      toast.fail("请输入操作金额");
      return false;
    }
    state.updating = true;
    try {
      const res = await reqUpDownPoints({
        UserId: props.uid,
        Action: Number(form.action),
        Amount: Number(form.amount)
      });
      state.updating = false;
      emit("update");
      toast.success((form.action == 4 ? "上分" : "下分") + res.message);
      setTimeout(() => {
        closed();
      }, 200);
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);

defineExpose({
  open
});
</script>
<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
